import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yb_zsyiji_androidflutter_pro/YBEngineer/YBBaseRouter/YBApplication.dart';
import 'package:yb_zsyiji_androidflutter_pro/YBEngineer/YBBaseRouter/YBNavigator.dart';
import 'package:yb_zsyiji_androidflutter_pro/YBHelper/YBColor/YBColor.dart';
import 'package:yb_zsyiji_androidflutter_pro/YBModule/YBMineModule/YBMineUserInfoPage/YBMineWxNumberEventBus.dart';
import 'package:yb_zsyiji_androidflutter_pro/YBModule/YBWorkTaiModule/YBFenXiangHuKePage/YBBaseProvider/YBFengMianImageEventBus.dart';
import 'package:yb_zsyiji_androidflutter_pro/YBNetWorkModule/YBBaseMineNetWork/YBBaseMineNetWork.dart';

import 'YBImageEventBus.dart';

class YBCameraSelectPopPage{

  static void getCameraSelectPop(BuildContext context){
    showModalBottomSheet(context: context, builder: (BuildContext context){
      return Container(
        height: 150,
        color: YBColor.white,
        child:Padding(
          padding:EdgeInsets.only(left: 0,right: 0),
          child: Column(
            children: [
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('拍摄'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    ImagePressedCamera(context: context);
                  },
                ),
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('从手机相册选择'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    imagePressed(context: context);
                  },
                ),
              ),
              Container(
                height: 8,
                color: YBColor.colorF5F5F7,
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('取消'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    });
  }


  static void getCameraSecondSelectPop(BuildContext context){
    showModalBottomSheet(context: context, builder: (BuildContext context){
      return Container(
        height: 150,
        color: YBColor.white,
        child:Padding(
          padding:EdgeInsets.only(left: 0,right: 0),
          child: Column(
            children: [
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('拍摄'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    ImagePressedSecondCamera(context: context);
                  },
                ),
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('从手机相册选择'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    imageSecondPressed(context: context);
                  },
                ),
              ),
              Container(
                height: 8,
                color: YBColor.colorF5F5F7,
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('取消'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    });
  }


  //图片第二张上传
  static Future<String> imageSecondPressed({BuildContext context}) async {
    PickedFile  _pickedFile = await ImagePicker().getImage(source:ImageSource.gallery);
    print('----图片-----${_pickedFile.path}');
    print('----图片-----$_pickedFile');

    var name = _pickedFile.path.substring(_pickedFile.path.lastIndexOf('/') + 1 , _pickedFile.path.length);

    print('----$name--------');
    print('----${_pickedFile.path}--------');

    FormData fordata = FormData.fromMap({
      "file":  await MultipartFile.fromFile(
        _pickedFile.path,
        filename: name,
      )
    });

    Dio _dio = Dio();

    print('------$fordata---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: fordata,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
      Map data = response.data as Map;
      print('------$data');
      String code = data['code'];
      print("object---$code");
      if (int.parse(code) == 0){
        mineWxNumberEventBus.fire(YBMineWxNumberEventBus(wxNumberCode: (data['url'] as String)));
      }
    }

  }

  //拍照-第二张图片上传
  static void ImagePressedSecondCamera({BuildContext context}) async {
    PickedFile  _pickedFile = await ImagePicker().getImage(source:ImageSource.camera,maxWidth: 400);
    print('----拍照-----${_pickedFile.path}');
    print('----拍照-----$_pickedFile');

    var name = _pickedFile.path.substring(_pickedFile.path.lastIndexOf('/') + 1 , _pickedFile.path.length);
    var image = await MultipartFile.fromFile(
      _pickedFile.path,
      filename: name,
    );

    FormData fordata = FormData.fromMap({
      "file":image,
    });

    Dio _dio = Dio();

    print('------$fordata---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: fordata,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
      Map data = response.data as Map;
      print('------$data');
      String code = data['code'];
      print("object---$code");
      if (int.parse(code) == 0){
        mineWxNumberEventBus.fire(YBMineWxNumberEventBus(wxNumberCode: (data['url'] as String)));
      }
    }


  }

  //图片上传
  static Future<String> imagePressed({BuildContext context}) async {
    PickedFile  _pickedFile = await ImagePicker().getImage(source:ImageSource.gallery);
    print('----图片-----${_pickedFile.path}');
    print('----图片-----$_pickedFile');

    var name = _pickedFile.path.substring(_pickedFile.path.lastIndexOf('/') + 1 , _pickedFile.path.length);

    print('----$name--------');
    print('----${_pickedFile.path}--------');

    FormData fordata = FormData.fromMap({
      "file":  await MultipartFile.fromFile(
          _pickedFile.path,
          filename: name,
      )
    });

    Dio _dio = Dio();

    print('------$fordata---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: fordata,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
       Map data = response.data as Map;
       print('------$data');
       String code = data['code'];
       print("object---$code");
       if (int.parse(code) == 0){
         imageStrEventBus.fire(YBImageEventBus(imageStr:(data["url"] as String)));
       }
    }

  }

  //拍照
  static void ImagePressedCamera({BuildContext context}) async {
    PickedFile  _pickedFile = await ImagePicker().getImage(source:ImageSource.camera,maxWidth: 400);
    print('----拍照-----${_pickedFile.path}');
    print('----拍照-----$_pickedFile');

    var name = _pickedFile.path.substring(_pickedFile.path.lastIndexOf('/') + 1 , _pickedFile.path.length);
    var image = await MultipartFile.fromFile(
      _pickedFile.path,
      filename: name,
    );

    FormData fordata = FormData.fromMap({
      "file":image,
    });

    Dio _dio = Dio();

    print('------$fordata---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: fordata,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
      Map data = response.data as Map;
      print('------$data');
      String code = data['code'];
      print("object---$code");
      if (int.parse(code) == 0){
        imageStrEventBus.fire(YBImageEventBus(imageStr:(data["url"] as String)));
      }
    }


  }
  


  static void getQuanCengInfoSelectPop(BuildContext context){
    showModalBottomSheet(context: context, builder: (BuildContext context){
      return Container(
        height: 150,
        color: YBColor.white,
        child:Padding(
          padding:EdgeInsets.only(left: 0,right: 0),
          child: Column(
            children: [
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('发布圈层'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    YBApplication.router.navigateTo(context, '/findQuanCengPage/findQuanCengPublishPage?urlInfo=${Uri.encodeComponent("圈层")}');
                  },
                ),
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('从手机相册选择'),
                    ),
                  ),
                  onTap: () async {
                   // YBNavigatorUtil.goDefaultBack(context);
                    loadAssets(context);
                  },
                ),
              ),
              Container(
                height: 8,
                color: YBColor.colorF5F5F7,
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('取消'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

 static Future<List> loadAssets(BuildContext context) async {

    List<Asset> resultList = List<Asset>();
    try {
      resultList = await MultiImagePicker.pickImages(
          maxImages: 9, enableCamera: true, materialOptions: MaterialOptions(
        actionBarColor: "#2D69E0",
        actionBarTitle: "选择图片",
        allViewTitle: "所有图片",
        useDetailsView: false,
        selectCircleStrokeColor: "#999999",
      ));
    }on Exception catch (e){
        EasyLoading.showError("图片选择错误,重新选择");
    }


    List<MultipartFile> multipartFileList = List<MultipartFile>();

    for(int i = 0; i < resultList.length; i++){
      ByteData byteData = await resultList[i].getByteData();
      List<int> imageData = byteData.buffer.asUint8List();
      MultipartFile multipartFile = MultipartFile.fromBytes(
        imageData,
        filename: "file$i.jpg",
        contentType: MediaType("image","jpg"),
      );

      print("object+++++++++++$multipartFile");

      multipartFileList.add(multipartFile);
    }
    print("0---$multipartFileList---0");

    FormData formData = FormData.fromMap({
      "file":multipartFileList,
    });

    Dio _dio = Dio();

    print('------$formData---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    EasyLoading.show(status: "上传中...");
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: formData,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
      print("--Object-${response.data}-");
      EasyLoading.dismiss();
      Map<String,dynamic> data = response.data as Map<String,dynamic>;
      print('------$data');
      String code = data['code'];
      print("object---$code");
      String urlStr = data["url"];
      print('object------$urlStr');
      if (int.parse(code) == 0){
        YBApplication.router.navigateTo(context, '/findQuanCengPage/findQuanCengPublishPage?urlInfo=${Uri.encodeComponent(urlStr)}');
      }
    }else{
      EasyLoading.dismiss();
    }

 }



  static void getCameraHuangMianSelectPop(BuildContext context){
    showModalBottomSheet(context: context, builder: (BuildContext context){
      return Container(
        height: 150,
        color: YBColor.white,
        child:Padding(
          padding:EdgeInsets.only(left: 0,right: 0),
          child: Column(
            children: [
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('拍摄'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    ImagePressedFengMianCamera(context: context);
                  },
                ),
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('从手机相册选择'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                    imageFengMianPressed(context: context);
                  },
                ),
              ),
              Container(
                height: 8,
                color: YBColor.colorF5F5F7,
              ),
              Container(
                child: InkWell(
                  child: Container(
                    height: 44,
                    child: Center(
                      child: Text('取消'),
                    ),
                  ),
                  onTap: () async {
                    YBNavigatorUtil.goDefaultBack(context);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    });
  }


  //图片第二张上传
  static Future<String> imageFengMianPressed({BuildContext context}) async {
    PickedFile  _pickedFile = await ImagePicker().getImage(source:ImageSource.gallery);
    print('----图片-----${_pickedFile.path}');
    print('----图片-----$_pickedFile');

    var name = _pickedFile.path.substring(_pickedFile.path.lastIndexOf('/') + 1 , _pickedFile.path.length);

    print('----$name--------');
    print('----${_pickedFile.path}--------');

    FormData fordata = FormData.fromMap({
      "file":  await MultipartFile.fromFile(
        _pickedFile.path,
        filename: name,
      )
    });

    Dio _dio = Dio();

    print('------$fordata---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: fordata,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
      Map data = response.data as Map;
      print('------$data');
      String code = data['code'];
      print("object---$code");
      if (int.parse(code) == 0){
        fengMianImageEventBus.fire(YBFengMianImageEventBus(fengMianImageStr: (data['url'] as String)));
      }
    }

  }

  //拍照-第二张图片上传
  static void ImagePressedFengMianCamera({BuildContext context}) async {
    PickedFile  _pickedFile = await ImagePicker().getImage(source:ImageSource.camera,maxWidth: 400);
    print('----拍照-----${_pickedFile.path}');
    print('----拍照-----$_pickedFile');

    var name = _pickedFile.path.substring(_pickedFile.path.lastIndexOf('/') + 1 , _pickedFile.path.length);
    var image = await MultipartFile.fromFile(
      _pickedFile.path,
      filename: name,
    );

    FormData fordata = FormData.fromMap({
      "file":image,
    });

    Dio _dio = Dio();

    print('------$fordata---');
    if (!ObjectUtil.isEmptyString(SpUtil.getString('token'))) {
      print('-----${SpUtil.getString('token')}');
      _dio.options.headers = {"Authorization":SpUtil.getString('token')};
      print("------------headers----------------");
    }
    Response response = await _dio.post("http://api.ubzone.cn/file/upload",
        data: fordata,queryParameters:{"sysCode":"xg_youbang"});
    if (response.statusCode == 200) {
      Map data = response.data as Map;
      print('------$data');
      String code = data['code'];
      print("object---$code");
      if (int.parse(code) == 0){
        fengMianImageEventBus.fire(YBFengMianImageEventBus(fengMianImageStr: (data['url'] as String)));
      }
    }


  }



}
